package com.centling.smartSealForPhone.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.centling.smartSealForPhone.BuildConfig;
import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.adapter.RvBlueListAdapter;
import com.centling.smartSealForPhone.bean.LoginBean;
import com.centling.smartSealForPhone.constants.GlobalData;
import com.centling.smartSealForPhone.constants.SPConstants;
import com.centling.smartSealForPhone.utils.ControlUtil;
import com.centling.smartSealForPhone.utils.LogUtil;
import com.centling.smartSealForPhone.utils.ParseBluetoothData;
import com.centling.smartSealForPhone.utils.SPUtil;
import com.centling.smartSealForPhone.utils.ShowToast;
import com.google.gson.Gson;
import com.wsdk.service.BluetoothLeService;

import java.util.ArrayList;
import java.util.List;

public class BluetoothListActivity extends BaseActivity {

    private static final int OPEN_BLUE_DIALOG = 1000;
    private BluetoothAdapter bluetoothAdapter;
    private List<BluetoothDevice> devices = new ArrayList<>();
    private boolean isScanning = false;
    private RecyclerView recyclerView;
    private LoginBean loginBean;

    private String macAddress = "";
    public int successPosition = -1;
    public int connPosition = -1;

    private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            LogUtil.d("Search Bluetooth Device:" + device.getName() + " " + device.getAddress());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    addDeviceToList(device);
                }
            });
        }
    };

    private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                successPosition = -1;
                connPosition = -1;
                recyclerView.getAdapter().notifyDataSetChanged();
                startSearchBlueDevice();
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                mProcessDialog.dismiss();
                if (BuildConfig.DEBUG) {
                    ShowToast.shortTime("Blue List Connected");
                }
                GlobalData.isConnect = true;
                new ControlUtil().changeStamp();
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                byte[] data = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);

                if (ParseBluetoothData.isInit(data)) {
                    int ret;
                    if((ret = ParseBluetoothData.parseInit(data)) == 0) {
                        syncTimeV1();
                    } else if(ret == 1){
                        feedbackToServerAndFetchFourKey();
                    } else if(ret == 2){
                        feedbackToServerAndSyncTime();
                    } else {
                        ShowToast.shortTime("初始化失败");
                    }
                } else if (ParseBluetoothData.isChangeStamp(data)) {
                    new ControlUtil().stamp();
                } else if (ParseBluetoothData.parseOpenByte(data) == 0x00) {
                    Intent intentGuide = new Intent(mContext,
                            GuideActivity.class);
                    intentGuide.putExtra("macAddress", macAddress);
                    startActivity(intentGuide);
                    finish();
                } else if (ParseBluetoothData.isGetSN(data)) {
                    String sn = ParseBluetoothData.parseSN(data);
                    LogUtil.d("Bluetooth Parse SN:" + sn);

                    if (sn != null) {
                        if (sn.equals(loginBean.getEquipRegisterInfo().getSn())) {
                            ShowToast.shortTime("连接成功");
                            connPosition = -1;
                            successPosition = connPosition;
                            GlobalData.isConnect = true;
                            if (getIntent().getBooleanExtra("toReconnect", false)) {
                                BluetoothListActivity.this.setResult(RESULT_OK);
                                finish();
                                return;
                            }
                            // 如果是新设备
                            if ("-1".equals(loginBean.getEquipRegisterInfo().getEquipStatus())) {
                                if (GlobalData.versionV2) {
                                    fetchMKeyForInit();
                                } else {
                                    new ControlUtil(false).init();
                                }
                            } else {
                                Intent intent2 = new Intent(mContext, MainTabsActivity.class);
                                intent2.putExtra("loginbean", loginBean);
                                startActivity(intent2);
                                finish();
                            }
                        } else {
                            BluetoothLeService.disconnect();
                            connPosition = -1;
                            successPosition = -1;
                            recyclerView.getAdapter().notifyDataSetChanged();
                            ShowToast.shortTime("序列号与服务端不一致,已断开连接");
                        }
                    } else {
                        connPosition = -1;
                        recyclerView.getAdapter().notifyDataSetChanged();
                    }
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth_list);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        registerReceiver(bluetoothReceiver, intentFilter);

        recyclerView = findViewById(R.id.rv_bluetooth_list);

        findViewById(R.id.tv_bluetooth_list_title).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                new ControlUtil().fetchKey();
            }
        });

        initData();

        checkBTAvailable();
    }

    private void initData() {
        loginBean = getIntent().getParcelableExtra("loginbean");
        if (loginBean == null) {
            loginBean = new Gson().fromJson(SPUtil.getString(SPConstants.LOGIN_JSON), LoginBean.class);
        }
        macAddress = loginBean.getEquipRegisterInfo().getBlueToothMac();
        LogUtil.d("Need Connect Bluetooth Address:" + macAddress);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        RvBlueListAdapter listAdapter = new RvBlueListAdapter(mContext, devices);
        listAdapter.setOnItemClickListener(new RvBlueListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (isScanning) {
                    stopSearch();
                }
                connPosition = position;
                recyclerView.getAdapter().notifyDataSetChanged();
                connectDevice(devices.get(position));
            }
        });
        recyclerView.setAdapter(listAdapter);
    }

    private void checkBTAvailable() {
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            ShowToast.shortTime("您的手机不支持蓝牙");
            finish();
            return;
        }
        BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = manager.getAdapter();
        if (bluetoothAdapter == null) {
            ShowToast.shortTime("设备不支持蓝牙");
            finish();
            return;
        }
        startSearchBlueDevice();
    }

    private void startSearchBlueDevice() {
        isScanning = true;
        devices.clear();
        recyclerView.getAdapter().notifyDataSetChanged();
        bluetoothAdapter.startLeScan(leScanCallback);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, OPEN_BLUE_DIALOG);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopSearch();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(bluetoothReceiver);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OPEN_BLUE_DIALOG && resultCode == RESULT_OK) {
            startSearchBlueDevice();
        }
    }

    private void connectDevice(BluetoothDevice connectedDevice) {
        Intent intent = new Intent(this, BluetoothLeService.class);
        intent.putExtra("DEVICE_ADDRESS", connectedDevice.getAddress());
        macAddress = connectedDevice.getAddress();
        sn = SPUtil.getString(SPConstants.EQUIPSN);
        startService(intent);
    }

    private void stopSearch() {
        isScanning = false;
        bluetoothAdapter.stopLeScan(leScanCallback);
    }

    private long preNotifyTime = 0;
    private final static long NOTIFY_INTERVAL = 2000;

    private void addDeviceToList(BluetoothDevice device) {
        if (!devices.contains(device)) {
            if ("HMSoft".equals(device.getName())) {
                devices.add(device);
            }

            long curTime = System.currentTimeMillis();
            if (curTime - preNotifyTime > NOTIFY_INTERVAL) {
                preNotifyTime = curTime;
                recyclerView.getAdapter().notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        BluetoothLeService.disconnect();
        devices.clear();
        finish();
        startActivity(new Intent(mContext, LoginActivity.class));
    }
}
